'''A module designed to correct peoples 401 (AOL) speech impediments.'''
############################################################################
#    Copyright (C) 2006 by Robert Small                                    #
#    SmallR2002@Gmail.com                                                  #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

__module_name__        = "bccorrector"
__module_version__     = "0.0.2"
__module_description__ = "A module designed to correct peoples 401 (AOL) speech impediments."

# 
# 0.0.2  Added in a few corrections to make it play nicely with other plugins. Also added
#       into bottlecap.py the priority of the hook, hopefully this should prevent *any* nasty
#       play with other plugins/scripts/modules.
# 
# 0.0.1  Split from main module
# 

import xchat
import string #IGNORE:W0402
import sys
import os

if (sys.path.count(os.path.dirname(__file__)) == 0):
    sys.path.append(os.path.dirname(__file__))

#  Pretty much essential.
import bcsettings
import bcmisc

if (bcsettings.modules_to_load.count("bcnotify") > 0):
    import bcnotify

#Fix for "RuntimeError: maximum recursion depth exceeded in cmp", seems to be only a temporary fix.
sys.setrecursionlimit(2000)

def do_corrections(word, word_eol, userdata): #IGNORE:W0613
    '''
    Correct the incoming data.
    @param word: all the data you need to work with, chopped up into small parts.
    @type word: string
    @param word_eol: all the data you need to work with, chopped from wherever you're starting from.
    @type word_eol: string
    @param userdata: custom object to pass back.
    @type userdata: object
    '''
    #FIXME: Pylint raises too many branches, this must be fixed in v2.
    context = xchat.get_context()

    changed = False
    
    capschange = False
    
    if (len(word) > 1) and (word[1] == " "):
        return xchat.EAT_NONE
    elif (len(word) == 1):
        return xchat.EAT_NONE
    
    
    cngword = word[1].strip(" ")
    
    if (cngword != word[1]):
        word[1] = cngword
        changed = True
    
    
    if (word[1].count(" ") > 0):
        words = word[1].split(" ")
        
        newwords = [bcmisc.aol.get(w.lower(), w) for w in words]
        
        cngword = newwords[0].capitalize()
        
        if (len(filter(string.lowercase.__contains__, word[1])) < len(filter(string.uppercase.__contains__, word[1]))) and (len(word[1]) > 2):
            for i, w in enumerate(newwords):
                if (i > 0) and (is_url(newwords[i]) == 0) and (newwords[i] != newwords[i].lower()):
                    newwords[i] = newwords[i].lower()
                    changed = True
                    
            #Next
            capschange = True
        
        
        if (cngword != newwords[0]) and (is_url(newwords[0]) == 0):
            newwords[0] = cngword
            changed = True
        
        
        #We should have a nice set of stuff done now! Time to correct caps.
        
        newwords = [bcmisc.caps.get(w.lower(), w) for w in newwords]
        
        if (words != newwords):
            changed = True
            
            if ((bcsettings.show_corrections == True) and (changed == True)):
                for i, w in enumerate(newwords):
                    if (words[i] != newwords[i]) and (i > 0):
                        newwords[i] = '\x0305' + newwords[i] + '\x03'
                    
                #Next
            
            
            word[1] = ""
            for i, w in enumerate(newwords):
                word[1] = word[1] + w + " "
            #Next
            word[1] = word[1].strip(" ")
            
            if (capschange == True):
                word[1] = word[1] + " [caps]"
        
        
        if changed:
#                        if (bcsettings.modules_to_load.count("bcnotify") > 0):
#                                bcnotify.libnotify_send(word[0] + " spoke in " + xchat.get_info('channel'), "* " + word[0] + " " + word[1], bcsettings.libnotify_urgency_cm)
            context.emit_print("Channel Message", *word)
            return xchat.EAT_ALL
        else:
            if (bcsettings.modules_to_load.count("bcnotify") > 0):
                bcnotify.libnotify_send(bcmisc.clean_text(word[0]) + " spoke in " + xchat.get_info('channel'), "<" + bcmisc.clean_text(word[0]) + "> " + word[1], bcsettings.libnotify_urgency_cm)
            return xchat.EAT_NONE
        
    #elif (string search):
    else:
        if word[1] in bcmisc.aol:
            word[1] = bcmisc.aol[word[1]]
            changed = True
        
        
        cngword = word[1].capitalize()
        
        if (cngword != word[1]) and (is_url(word[1]) == 0):
            word[1] = cngword
            changed = True
        
        
        if changed:
            context.emit_print("Channel Message", *word)
            return xchat.EAT_ALL
        else:
            if (bcsettings.modules_to_load.count("bcnotify") > 0):
                bcnotify.libnotify_send(bcmisc.clean_text(word[0]) + " spoke in " + xchat.get_info('channel'), "<" + bcmisc.clean_text(word[0]) + "> " + word[1], bcsettings.libnotify_urgency_cm)
            return xchat.EAT_NONE
        
    
#End of sub

def is_url(url):
    '''
    Check if it's a URL.
    @param url: the URL.
    @type url: string
    '''
    #Firstly check if it starts with any of the normal things.
    if (True in map(url.startswith, (bcmisc.starters))):
        return 1
    
    
    #Or ends with one of the normal things...
    if (True in map(url.endswith, (bcmisc.tlds))):
        return 1
    #End if
    
    #Or has .tld/ in.
    if [x for x in url if x in bcmisc.tlds2 ]:
        return 1
    else:
        return 0
    #End if
    
    return 0